package my.suveng.oauth2.config.auth;

import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import my.suveng.oauth2.service.user.impl.UserServiceImpl;
import my.suveng.util.log.PlusLogFactoryHutool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * spring oauth 提供的 user服务
 * 
 * @author suwenguang
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    // hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool())
            .getLog(CallerUtil.getCaller().getName());

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isBlank(username)) {
            log.error("用户名不能为空");
            throw new UsernameNotFoundException("用户名不能为空");
        }

        // user信息
        User user = userServiceImpl.getUserInfoByUsername(username);

        if (ObjectUtil.isEmpty(user)) {
            log.error("用户信息为空");
            throw new UsernameNotFoundException("用户信息为空");
        }

        return user;
    }

}
